<?php

namespace App\Models;

//use App\Models\Traits\ReturnSharpStockWithoutSku;
use Carbon\Carbon;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Log;

class SharpToGoods extends BaseModel
{
	//use ReturnSharpStockWithoutSku;
	protected $fillable = [
		'sharp_id',
		'goods_id',
		'goods_sku_id',
		'stock',
		'sell',
	];
	
	public function goods()
	{
		return $this->belongsTo(Goods::class)->withTrashed();
	}
	
//	public function sharp()
//	{
//		return $this->belongsTo(Sharp::class);
//	}
	
	public function goodsToClassify()
	{
		return $this->hasMany(GoodsToClassify::class);
	}
	
	public function setPriceAttribute($value)
	{
		$this->attributes['price'] = $value * 100;
	}
	
	public function getPriceAttribute($value)
	{
		return $value / 100;
	}
	
	public function setLinePriceAttribute($value)
	{
		$this->attributes['line_price'] = $value * 100;
	}
	
	public function getLinePriceAttribute($value)
	{
		return $value / 100;
	}
	
	/**返回秒杀sku库存
	 * @param array $sku_ids
	 * @param int $sharp_id
	 * @return bool|int
	 */
	public static function prepareReturnStock($sharp_id = 0)
	{
		if (empty($sharp_id)) {
			return false;
		}
		// 查找秒杀商品库存大于0的
		$sharp = Sharp::with(['sharpGoods' => function ($q) {
			$q->whereNotNull('goods_sku_id')->where('stock', '>', 0);
		}])->find($sharp_id);
		
		if (empty($sharp->sharpGoods->toArray())) {
			return false;
		}
		
		$returns = $sharp->sharpGoods->pluck('stock', 'goods_sku_id')->toArray();
		
		$sku = GoodsSku::whereIn('id', array_keys($returns))->get(['id', 'stock']);
		
		foreach ($sku as $item) {
			static $data = [];
			$item->stock += Arr::get($returns, $item->id, 0);
		}

		$res = updateBatch('goods', $sku->toArray());
		return $res;
	}
	
	/**
	 * 返回sku库存
	 * @param array $sku
	 * @param array $needs
	 * @return bool|int
	 */
	public static function returnStock($tableName = 'goods_sku', $sku = [], $needs = [])
	{
		if (empty($sku) || empty($needs)) {
			return false;
		}
		$returns = [];
		foreach ($sku as $k => $v) {
			if (isset($needs[$v['id']])) {
				$stock = $v['stock'] + $needs[$v['id']];
				$returns[] = ['id' => $v['id'], 'stock' => $stock];
			}
		}

		$res = updateBatch($tableName, $returns);
		return $res;
	}
	
	/**
	 * 减少参与秒杀sku库存
	 * @param array $needs
	 * @return bool|int|string
	 */
	static public function prepareReduceStock($needs = [])
	{
		$sku = GoodsSku::whereIn('id', array_keys($needs))->get(['id', 'stock'])->toArray();
		if (empty($sku)) {
			return false;
		}
		self::reduceStock($sku, $needs);
		return true;
	}
	
	/**
	 * 减少sku的库存
	 * @param array $sku
	 * @param array $needs
	 */
	static public function reduceStock($sku = [], $needs = [])
	{
		if (empty($sku) || empty($needs)) {
			return false;
		}
		$reduce = [];
		foreach ($sku as $k => $v) {
			$stock = $v['stock'] - $needs[$v['id']];
			$reduce[] = ['id' => $v['id'], 'stock' => $stock];
		}
		$res = self::isEnoughStock($reduce);
		if ($res !== true) {
			return $res;
		}
		$res = updateBatch('goods_sku', $reduce);
		return $res?true:'数据库出错';
	}
	
	/**
	 * 判断库存是否充足
	 * @param $reduce
	 * @return bool|string
	 */
	static public function isEnoughStock($reduce)
	{
		if (empty($reduce)) {
			return false;
		}
		foreach ($reduce as $k => $v) {
			if ($v['stock'] < 0) {
				$sku = GoodsSku::with(['goods:id,name'])->find($v['id']);
				return $sku->goods->name .'规格['. $sku->attribute_string . ']库存不足';
			}
		}
		
		return true;
	}
	
	/**
	 * 定时任务检查结束的秒杀活动，返回剩余库存
	 */
	static public function scheduleReturnAllStock()
	{
		$sharp = Sharp::with(['sharpGoods' => function ($q) {
			$q->where('stock', '>', 0)->selectRaw('id,sharp_id,goods_id,goods_sku_id,stock');
		}])->where('active_end', '<=', Carbon::now())->get();

		if (empty($sharp)) {
			Log::info('没有秒杀活动库存需要返回');
		}
		
		$data = collect(Arr::collapse($sharp->pluck('sharpGoods')->toArray()));
		
		// 返回所有带sku的
		$sku_res = self::scheduleReturnSkuStock($data->whereNotNull('goods_sku_id'));
		// 返回不带sku的
		$goods_res = self::scheduleReturnStock($data->whereNull('goods_sku_id'));
		
		if ($goods_res == true && $sku_res == true) {
			Log::info('返回秒杀剩余库存成功');
			print_r('返回秒杀剩余库存成功'.PHP_EOL);
		} else {
			Log::info('返回秒杀剩余库存失败');
			print_r('返回秒杀剩余库存失败'.PHP_EOL);
		}
	}
	
	static public function scheduleReturnSkuStock($sku = [])
	{
		if (empty($sku)) {
			return false;
		}
		
		$skus = GoodsSku::whereIn('id', $sku->pluck('goods_sku_id'))->get(['id', 'stock']);
		$res = self::returnStock('goods_sku',$skus, $sku->pluck('stock', 'goods_sku_id'));
		return $res;
	}
	
	static public function scheduleReturnStock($goods = [])
	{
		if (empty($goods)) {
			return false;
		}
		
		$sku = Goods::whereIn('id', $goods->pluck('goods_id'))->withTrashed()->get(['id', 'stock']);
		
		$res = self::returnStock('goods', $sku, $goods->pluck('stock', 'goods_id'));
		return $res;
	}
}
